import com.jogamp.opengl.GLCapabilities;
import com.jogamp.opengl.GLProfile;
import com.jogamp.opengl.awt.GLCanvas;
import com.jogamp.opengl.util.FPSAnimator;
import org.yaml.snakeyaml.Yaml;

import javax.swing.*;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

public class GUI {

    // 单例
    private static GUI gui;

    BasicFrame basicFrame;
    GLCanvas glCanvas;
    JFrame frame;
    FPSAnimator animator;

    static Config config = new Config();


    public static GUI getInstance() {
        if (gui == null) {
            try {
                loadConfiguration();
            } catch (FileNotFoundException e) {
                System.out.println("无法找到文件config.yaml，将使用默认配置");
            }
            gui = new GUI();
        }
        return gui;
    }

    private static void loadConfiguration() throws FileNotFoundException {
        InputStream inputStream = new FileInputStream("config.yaml");
        config = new Yaml().loadAs(inputStream, Config.class);
        System.out.println("加载配置文件");
        System.out.println(config);
    }


    private GUI() {
        final GLProfile profile = GLProfile.getDefault();
        GLCapabilities capabilities = new GLCapabilities(profile);
        basicFrame = new BasicFrame(config.getBoardHeight(), config.getBoardWidth());

        glCanvas = new GLCanvas(capabilities);
        glCanvas.setSize(config.getWidth(), config.getHeight());
        glCanvas.addGLEventListener(basicFrame);

        frame = new JFrame(config.getFrameName());
        frame.add(glCanvas);
        frame.setSize(config.getWidth(), config.getHeight());
        frame.setVisible(true);

        animated();
    }



    public void animated() {
        animator = new FPSAnimator(config.getFpsLimit());
        animator.add(glCanvas);
        animator.start();
        animator.setUpdateFPSFrames(3, null);

        // 实时更新fps
        new Thread(() -> {
            for (;;) {
                System.out.println("FPS: " + animator.getLastFPS());
                try {
                    Thread.sleep(config.getFpsUpdateGap());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }


    public static void main(String[] args) {
        GUI.getInstance();
    }
}
